package cn.com.okgotest;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v7.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.List;

import cn.com.okgotest.fragment.CookieFragment;
import cn.com.okgotest.fragment.DownloadFragment;
import cn.com.okgotest.fragment.GetFragment;
import cn.com.okgotest.fragment.HttpsFragment;
import cn.com.okgotest.fragment.OkHttp2Fragment;
import cn.com.okgotest.fragment.ParsersFragment;
import cn.com.okgotest.fragment.PostFragment;
import cn.com.okgotest.fragment.base.BaseFragment;
import cn.com.okgotest.fragment.base.FragmentPagerAdapter;
import cn.com.okgotest.fragment.base.FragmentViewPager;

public class MainActivity extends AppCompatActivity{

    private List<BaseFragment> fragments = new ArrayList<>();
    private FragmentViewPager viewPager;

    private String tabs[]={"GET 请求","POST 请求","文件下载","Cookie 管理","Json解析","Https","OkHttp2"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        BaseFragment fragment = fragments.get(viewPager.getCurrentItem());
        fragment.onActivityResult(requestCode, resultCode, data);
    }

    private void init(){
        TabLayout tabLayout=findViewById(R.id.tabLayout);
        for(String s:tabs){
            tabLayout.addTab(tabLayout.newTab());
        }
        viewPager = findViewById(R.id.mViewPager);
        fragments.add(new GetFragment());
        fragments.add(new PostFragment());
        fragments.add(new DownloadFragment());
        fragments.add(new CookieFragment());
        fragments.add(new ParsersFragment());
        fragments.add(new HttpsFragment());
        fragments.add(new OkHttp2Fragment());
        viewPager.setScanScroll(true);
        viewPager.setOffscreenPageLimit(fragments.size());
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setupWithViewPager(viewPager);
    }

    PagerAdapter adapter = new FragmentPagerAdapter(getFragmentManager()) {
        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return tabs[position];
        }
    };
}
